package com.avic.modules.log.rest;

import com.avic.dozer.service.IGenerator;
import com.avic.modules.log.domain.vo.LogEnumeration;
import com.avic.modules.log.service.LogsService;
import com.avic.modules.log.service.dto.LogDto;
import com.avic.modules.log.service.dto.LogQueryCriteria;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangzikang
 * @date 2022-08-14
 */
@Api(tags = "日志管理: 操作日志接口")
@RestController
@RequestMapping("/api/log")
@AllArgsConstructor
public class LogsController {

    private final IGenerator generator;
    private final LogsService logService;

    /**
     * 查看操作日志
     * @param criteria
     * @return
     */
    @ApiOperation("查看操作日志")
    @GetMapping
    @PreAuthorize("@el.check('admin','log:list')")
    public ResponseEntity<Object> getRoles(LogQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(logService.queryAll(criteria,pageable), HttpStatus.OK);
    }

    /**
     * 查看操作日志动作
     * @return
     */
    @ApiOperation("查看操作日志动作")
    @GetMapping("/action")
    public ResponseEntity<Object> getAction(){
        List<Map<String, Object>> actionLog = new ArrayList<>();
        for(LogEnumeration  acLog:LogEnumeration.values()){
            Map<String, Object> map = new LinkedHashMap<>(2);
            map.put("name",acLog.getCode());
            map.put("value",acLog.getMessage());
            actionLog.add(map);
        }
        return new ResponseEntity<>(actionLog,HttpStatus.OK);
    }

    @ApiOperation("导出操作日志时间")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('admin','log:download')")
    public void download(HttpServletResponse response, LogQueryCriteria criteria, Pageable pageable) throws IOException, ParseException {
        logService.download(generator.convert(logService.queryAlls(criteria,pageable), LogDto.class),response);
    }

    @GetMapping(value = "/user")
    @ApiOperation("用户日志查询")
    public ResponseEntity<Object> getUserLogs(LogQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(logService.queryAllByUser(criteria, pageable), HttpStatus.OK);
    }

}
